#include "shared_library.h"
#include <string>
#include <map>

using namespace std;
USE_YDI_DATABASE_NS

typedef connection* (BAZINGA4_CALL *create_func)();
typedef void (BAZINGA4_CALL *release_func)(connection*);

string error;
static map< connection*, shared_library* > module_map;

connection* create_connection(const char* module_name)
{
	if(!module_name)
	{
		error = "invalid parameter passed";
		return NULL;
	}

	connection* conn = NULL;
	SharedLibrary* library = NULL;
	try
	{
		library = new shared_library(module_name);
	}
	catch (const char* e)
	{
		error = e;
		return NULL;		
	}

	create_func func = (create_func)library->address("create_connection");
	if (func)
	{
		conn = func();
		if (conn)
		{
			module_map[conn] = library;
		}
		else
		{
			error = "Failed to Create connection!";
			SAFEDELETE(library);
			return NULL;
		}
	}
	else
	{	
		error = "Failed to Get Function create_connection!";
		SAFEDELETE(library);
		return NULL;
	}
	return conn;
}

void release_connection(connection* conn)
{
	if (module_map.find(conn) != module_map.end())
	{
		shared_library* library = module_map[conn];
		release_func r = (release_func)library->address("release_connection");
		if (r)
		{
			r(conn);
		}
		SAFEDELETE(library);
		module_map.erase(conn);
	}
}

